package net.nio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 将字符串写入文件
 *
 * @author 王霄
 * @date 2021/8/21 17:15
 */
public class FileChannel_01 {
    public static void main(String[] args) throws IOException {
        var s = "你好,xad";
        var fileOutputStream = new FileOutputStream("d:\\aaa.txt");

        //获取通道
        var channel = fileOutputStream.getChannel();

        //创建一个缓冲区
        var buffer = ByteBuffer.allocate(1024);

        //将数据放入缓冲区(此时缓冲区只能写数据)
        buffer.put(s.getBytes());

        //读写翻转
        buffer.flip();

        //把缓冲区的数据写入通道
        channel.write(buffer);

        //关闭流
        fileOutputStream.close();
    }
}
